<template>
  <div class="container-div">
    <el-collapse-transition>
      <el-row v-show="searchShow" class="search-collapse">
        <el-form ref="searchForm" :model="formSearch" label-width="80px" size="small">
          <el-row :gutter="5">
            <el-col :span="8">
              <el-form-item label="角色名称" prop="name">
                <el-input v-model.trim="formSearch.name" placeholder="角色名称" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="角色标识" prop="code">
                <el-input v-model.trim="formSearch.code" placeholder="角色标识" clearable/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="5">
            <el-col :span="5">
              <el-form-item label="角色状态" prop="status">
                <el-select v-model="formSearch.status" placeholder="角色状态">
                  <el-option label="所有" value=""/>
                  <el-option
                    v-for="item in dictOptions"
                    :key="item.dictCode"
                    :label="item.dictLabel"
                    :value="item.dictValue"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="创建日期">
                <el-date-picker
                  v-model="beginEndDate"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  @change="beginEndDateChange"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item>
                <el-button type="primary" round icon="el-icon-search" @click="onSubmit">搜索</el-button>
                <el-button type="reset" round icon="el-icon-refresh" @click="reset">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
    </el-collapse-transition>
    <el-row class="select-table">
      <el-row class="mb10">
        <el-col :span="20">
          <el-button v-permission="[&quot;system:role:add&quot;]" type="primary" icon="el-icon-plus" size="small" @click="handleAddUpdate()">新增</el-button>
          <el-button v-permission="[&quot;system:role:edit&quot;]" :disabled="isEditDisabled" type="warning" icon="el-icon-edit" size="small" @click="handleAddUpdate(mulSelection[0])">修改</el-button>
          <el-button v-permission="[&quot;system:role:deletebatch&quot;]" :disabled="isDeleteDisabled" type="danger" icon="el-icon-delete" size="small" @click="handleBatchDelete">删除</el-button>
        </el-col>
        <el-col :span="4">
          <el-button-group>
            <el-button icon="el-icon-search" size="small" @click="showSearch"/>
            <el-button icon="el-icon-refresh" size="small" @click="searchList"/>
            <el-dropdown :hide-on-click="false" trigger="click">
              <el-button icon="el-icon-tickets" size="small"/>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-checkbox v-model="bIdColShow">角色编号</el-checkbox>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-checkbox v-model="bNameColShow">角色名称</el-checkbox>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-checkbox v-model="bCodeColShow">权限标识</el-checkbox>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-checkbox v-model="bSortColShow">显示排序</el-checkbox>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-checkbox v-model="bStatusColShow">状态</el-checkbox>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-checkbox v-model="bCreateTimeColShow">创建时间</el-checkbox>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-checkbox v-model="bToolColShow">操作</el-checkbox>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-button-group>
        </el-col>
      </el-row>
      <el-row>
        <el-table
          v-loading="tabLoading"
          :data="dataList"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="55"/>
          <el-table-column
            v-if="bIdColShow"
            prop="id"
            label="角色编号"
            width="120"/>
          <el-table-column
            v-if="bNameColShow"
            prop="name"
            label="角色名称"
            width="150"/>
          <el-table-column
            v-if="bCodeColShow"
            prop="code"
            label="角色标识"
            width="150"/>
          <el-table-column
            v-if="bSortColShow"
            prop="sort"
            label="排序"
            width="80"/>
          <el-table-column
            v-if="bStatusColShow"
            prop="status"
            label="状态"
            width="80">
            <template slot-scope="scope">
              <span
                v-for="dictOption in dictOptions"
                v-if="scope.row.status===dictOption.dictValue"
                :key="dictOption.dictCode"
                :class="['badge',dictOption.listClass]">{{ dictOption.dictLabel }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="bCreateTimeColShow"
            prop="createTime"
            label="创建时间"/>
          <el-table-column
            v-if="bToolColShow"
            label="操作"
            width="150">
            <template slot-scope="scope">
              <el-tooltip content="修改角色" placement="top">
                <el-button v-permission="[&quot;system:role:edit&quot;]" type="warning" icon="el-icon-edit" size="mini" circle @click="handleAddUpdate(scope.row)"/>
              </el-tooltip>
              <el-tooltip content="删除角色" placement="top">
                <el-button v-permission="[&quot;system:role:delete&quot;]" type="danger" icon="el-icon-delete" size="mini" circle @click="handleDelete(scope.row)"/>
              </el-tooltip>
              <el-tooltip content="角色授权" placement="top">
                <el-button v-permission="[&quot;system:role:grant&quot;]" type="success" icon="el-icon-circle-check-outline" size="mini" circle @click="handleGrant(scope.row)"/>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-row>
    <!-- 部门设置 对话框 -->
    <addUpdate
      v-if="addUpdateFormVisible"
      ref="addUpdateDialog"
      @refreshDataList="searchList"/>
    <!-- 授权对话框 -->
    <grant v-if="grantDialogVisible" ref="grantDialog"/>
  </div>
</template>

<script>
import addUpdate from './add-update'
import grant from './grant'

import { getDictLabel } from '@/utils'

import resultCode from '@/utils/resultCode'
import { getDictByType } from '@/api/dict'
import { getList, deleteOne, deleteBatch } from '@/api/role'

import permission from '@/directive/permission/index.js' // 权限判断指令
import checkPermission from '@/utils/permission' // 权限判断函数

// 表格动态错乱，可在el-table-column属性加上:key="Math.random()"
export default {
  name: 'Role',
  components: { addUpdate, grant },
  directives: { permission },
  data() {
    return {
      beginEndDate: null,
      searchShow: true,
      isEditDisabled: true,
      isDeleteDisabled: true,
      bSortColShow: true,
      bStatusColShow: true,
      bCodeColShow: true,
      bToolColShow: true,
      bIdColShow: true,
      bNameColShow: true,
      bCreateTimeColShow: true,
      tabLoading: false,
      dictOptions: [],
      formSearch: {
        name: null,
        code: null,
        status: null,
        beginDate: null,
        endDate: null
      },
      dataList: [],
      mulSelection: [],
      addUpdateFormVisible: false,
      grantDialogVisible: false
    }
  },
  created() {
    this.getDictList()
    this.searchList()
  },
  methods: {
    checkPermission,
    beginEndDateChange: function() {
      console.log('=====beginEndDateChange=====')
      console.log(this.beginEndDate)
      if (this.beginEndDate) {
        this.formSearch.beginDate = this.beginEndDate[0]
        this.formSearch.endDate = this.beginEndDate[1]
      } else {
        this.formSearch.beginDate = null
        this.formSearch.endDate = null
      }
    },
    showSearch: function() {
      this.searchShow = !this.searchShow
    },
    getDictList: function() {
      getDictByType('sys_normal_disable').then(response => {
        const result = response.data// 请求接口返回的内容
        if (result.code === resultCode.SUCCESS) {
          this.dictOptions = result.data
          console.log('=========dictOptions=========')
          console.log(result.data)
        }
      })
    },
    searchList: function() {
      this.tabLoading = true
      getList(this.formSearch).then(response => {
        const result = response.data// 请求接口返回的内容
        if (result.code === resultCode.SUCCESS) {
          console.log('=========datalist=========')
          console.log(result.data)
          this.dataList = result.data
        }
        this.tabLoading = false
      })
    },
    handleSelectionChange: function(val) {
      this.mulSelection = val
      console.log(this.mulSelection)
      console.log(val.length)

      if (this.mulSelection.length > 0) {
        this.isDeleteDisabled = false
        if (this.mulSelection.length == 1) {
          this.isEditDisabled = false
        } else {
          this.isEditDisabled = true
        }
      } else {
        this.isDeleteDisabled = true
        this.isEditDisabled = true
      }
    },
    onSubmit: function() {
      this.searchList()
    },
    reset: function() {
      this.$refs.searchForm.resetFields()
      this.beginEndDate = null
      this.formSearch.beginDate = null
      this.formSearch.endDate = null
    },
    handleAddUpdate: function(row) {
      this.addUpdateFormVisible = true
      this.$nextTick(() => {
        this.$refs.addUpdateDialog.init(this.dictOptions, row)
      })
    },
    handleDelete: function(row) {
      this.$confirm('此操作将删除【' + row.name + '】角色以及子角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOne(row.id).then(response => {
          const result = response.data// 请求接口返回的内容
          if (result.code === resultCode.SUCCESS) {
            this.$message.success('删除成功')
            this.searchList()
          }
        })
      }).catch(() => {

      })
    },
    handleGrant: function(row) {
      console.log('========row========')
      console.log(row.id)
      this.grantDialogVisible = true
      this.$nextTick(() => {
        this.$refs.grantDialog.init(row.id)
      })
    },
    handleBatchDelete: function() {
      let names = ''
      const ids = []
      this.mulSelection.forEach(row => {
        names += row.name + ' '
        ids.push(row.id)
      })
      console.log(ids)
      const strIds = ids.join(',')
      console.log('ids=' + strIds)
      this.$confirm('此操作将删除【' + names + '】角色以及子角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBatch(strIds).then(response => {
          const result = response.data// 请求接口返回的内容
          if (result.code === resultCode.SUCCESS) {
            this.$message.success('删除成功')
            this.searchList()
          }
        })
      }).catch(() => {

      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'status') {
          return getDictLabel(v[j], this.dictOptions)
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
